import re
from django.conf import settings
from django.contrib.auth import logout, login
from django.core.mail import send_mail
from django.db.models import Q
from django.http import HttpResponseForbidden,JsonResponse
from django.http import HttpResponsePermanentRedirect
from django.shortcuts import render
from django.urls import reverse
from django.views import View
from users.forms import RegisterForm,LoginForm,ForgetForm,UploadImageForm,UserInfoForm,ModifyPwdForm
from users.models import UserProfile,Banner
from users.util import generate_url
from utils.secret import SecretOauth
from utils.mixin_utils import LoginRequiredMixin
from operation.models import UserCourse,UserFavorite,UserMessage
from courses.models import Course
from organization.models import CourseOrg,Teacher
from django.core.paginator import Paginator
#我的消息
class MyMessageView(LoginRequiredMixin,View):
    def get(self,request):
        my_messages = UserMessage.objects.filter(Q(user = request.user.id)|Q(user=0),has_read=False)
        messages= Paginator(my_messages,5)

        return render(request, 'usercenter-message.html', {'messages': messages,"MEDIA_URL":settings.MEDIA_URL})








#我的收藏---公开课
class MyFavCourseView(LoginRequiredMixin,View):
    def get(self,request):
        my_courses = UserFavorite.objects.filter(user=request.user, fav_type=1)
        course_list = []
        for my_course in my_courses:
            course = Teacher.objects.filter(id=my_course.fav_id)
            course_list.append({'course_id': my_course.fav_id, 'course': course})
        return render(request, 'usercenter-fav-teacher.html', {
            'teacher_list': course_list,
            'MEDIA_URL': settings.MEDIA_URL
        })


#我的收藏---老师
class MyFavTeacherView(LoginRequiredMixin,View):
    def get(self,request):
        my_teachers = UserFavorite.objects.filter(user=request.user, fav_type=3)
        teacher_list = []
        for my_teacher in my_teachers:
            teacher = Teacher.objects.filter(id=my_teacher.fav_id)
            teacher_list.append({'teacher_id': my_teacher.fav_id, 'teacher': teacher})
        return render(request, 'usercenter-fav-teacher.html', {
            'teacher_list': teacher_list,
            'MEDIA_URL':settings.MEDIA_URL
        })

#我的收藏---课程学校
class MyFavOrgView(LoginRequiredMixin,View):
    def get(self,request):
        my_orgs = UserFavorite.objects.filter(user = request.user,fav_type = 2)
        org_list = []
        for my_org in my_orgs:
            org = CourseOrg.objects.filter(id = my_org.fav_id)
            org_list.append({'org_id':my_org.fav_id,'org':org})
        return render(request, 'usercenter-fav-org.html', {
            'org_list': org_list,
            'MEDIA_URL':settings.MEDIA_URL
        })

#我的课程
class MyCourseView(LoginRequiredMixin,View):
    def get(self,request):
        user_courses = UserCourse.objects.filter(user=request.user)
        return render(request, 'usercenter-mycourse.html',{
            'user_courses': user_courses,
            'MEDIA_URL':settings.MEDIA_URL
        })

#修改头像
class UploadImageView(LoginRequiredMixin,View):
    def post(self,request):
        user_data = request.POST
        image = request.FILES
        # print(type(image))
        form_data = UploadImageForm(user_data,image)
        res = form_data.is_valid()
        if res:
            user = request.user
            try:
                user.image = form_data.cleaned_data['image']
                user.save()
                return JsonResponse({
                        "status":"success",
                        "msg":'头像修改成功'
                        })
            except:
                return JsonResponse({
                    "status": "error",
                    "msg": '头像修改失败'
                })
        else:
            return JsonResponse({
                "status": "error",
                "msg": '头像修改失败'
            })

#用户中心
class UserInfoView(LoginRequiredMixin,View):
    def get(self,request):
        return render(request, 'usercenter-info.html',{
            'MEDIA_URL':settings.MEDIA_URL
        })
    def post(self,request):
        data = request.POST
        user_form = UserInfoForm(data)
        res = user_form.is_valid()
        id = request.user.id
        if res:
            username = user_form.cleaned_data['nick_name']
            address = user_form.cleaned_data['address']
            mobile = user_form.cleaned_data['mobile']
            birthday = user_form.cleaned_data['birthday']
            gender = user_form.cleaned_data['gender']
            # email = user_form.cleaned_data['email']
            # image = user_form.cleaned_data['image']
            UserProfile.objects.filter(id = id).update(
                nick_name = username,
                address = address,
                mobile = mobile,
                birthday = birthday,
                gender = gender,
            )
            return JsonResponse({"status":"success"})
        else:
            return JsonResponse({"status":"error"})

#验证密码
class ModifyView(View):
    def post(self,request):
        data = request.POST
        email = data.get('email')
        modify_form = ModifyPwdForm(data)
        if modify_form.is_valid():
            password1 = modify_form.cleaned_data['password1']
            password2 = modify_form.cleaned_data['password2']

            try:

                user = UserProfile.objects.get(email=email)
                if password1 == password2:
                    user.password=password1
                    user.save()
                    return render(request, 'login.html')
                else:
                    modify_form.errors.password = '密码不一致'
                    return render(request, 'password_reset.html', {'modify_form': modify_form})
            except:
                modify_form.errors.username = '用户不存在'
            return render(request, 'password_reset.html', {'modify_form': modify_form})
        modify_form.errors.msg = '修改失败'
        return render(request, 'password_reset.html', {'modify_form': modify_form})

#修改密码
class ResetView(View):
    def get(self,request,active_code):
        try:
            email = SecretOauth().loads(active_code)
            UserProfile.objects.get(email=email)
        except:
            return render(request, 'active_fail.html')
        return render(request, 'password_reset.html', {'email': email})

#忘记密码
class ForgetPwdView(View):
    def get(self,request):
        forget_form = ForgetForm()
        return render(request, 'forgetpwd.html', {'forget_form': forget_form})

    def post(self,request):
        data = request.POST
        forget_form = ForgetForm(data)
        res = forget_form.is_valid()
        if res:
            email = forget_form.cleaned_data['email']
            try:
                user = UserProfile.objects.get(email = email)
            except:
                return HttpResponseForbidden('邮箱不存在')

            try:
                send_mail(subject = '博学谷邮箱验证',message = '',from_email=settings.EMAIL_FROM,recipient_list=[email],
                          html_message = '<p><a href="%s">%s</a></p>'% (generate_url(email),generate_url(email)))
            except:
                return HttpResponseForbidden('邮箱发送失败')

            return render(request, 'send_success.html')
        else:
            return render(request, 'forgetpwd.html', {'forget_form': forget_form})


#注册
class RegisterView(View):
    def get(self,request):
        register_form = RegisterForm()
        return render(request,'register.html',{'register_form':register_form})

    def post(self,request):
        #1.获取前端传递的表单数据
        data = request.POST
        #2.验证表单数据
        register_form = RegisterForm(data)
        res = register_form.is_valid()  # 验证成功返回True，验证失败返回False
        if res:
            #表单数据验证成功 后端逻辑
            email = register_form.cleaned_data['email']
            password = register_form.cleaned_data['password']
            # if not re.match(r'^[0-9A-Za-z]{6,20}$',password):
            #     register_form.errors.password = '请输入6-20位密码'
            #     return render(request, 'register.html', {'register_form': register_form})
            # if not re.match(r'^$',email):
            #     register_form.errors.email = '邮箱错误'
            #     return render(request, 'register.html', {'register_form': register_form})
            try:
                user = UserProfile.objects.get(email = email)
                register_form.errors.email = '邮箱已存在'
                return render(request, 'register.html', {'register_form': register_form})
            except:
                user = UserProfile.objects.create(
                    username = email,
                    email = email,
                    password = password,
                )
                login(request,user)
            return render(request, 'index.html',{'MEDIA_URL':settings.MEDIA_URL})

        else:
            #失败 后端逻辑
            return render(request, 'register.html', {'register_form': register_form})


#登出
class LogoutView(View):
    def get(self, request):
        logout(request)
        response = render(request, 'login.html')
        response.delete_cookie('username')
        return response

#登录
class LoginView(View):
    #登录页面
    def get(self,request):
        return render(request,'login.html')
    #接受登录数据
    def post(self,request):
        data = request.POST
        login_form = LoginForm(data)
        res = login_form.is_valid()
        if res:
            #从表单中提取数据
            email = login_form.cleaned_data['username']
            password = login_form.cleaned_data['password']
            #验证成功 判断数据库是否存在
            # if not re.match(r'^[0-9A-Za-z]{6,20}$',password):
            #     register_form.errors.password = '请输入6-20位密码'
            #     return render(request, 'register.html', {'register_form': register_form})
            # if not re.match(r'^$',email):
            #     register_form.errors.username = '邮箱错误'
            #     return render(request, 'register.html', {'register_form': register_form})
            from django.contrib.auth import authenticate, login
            # user = authenticate(email=email, password=password)
            try:
                user = UserProfile.objects.get(email = email,password = password)
            except:
                user = None
            if user is None:
                return HttpResponseForbidden("用户不存在")
            login(request,user)
            return HttpResponsePermanentRedirect(reverse('index'))
        else:
            #失败
            # login_form.errors = '表单数据错误'
            return render(request, 'login.html', {'form_errors': login_form.errors})


#首页
class IndexView(View):
    def get(self,request):
        all_banners = Banner.objects.all()
        courses = Course.objects.all()
        banner_courses = Course.objects.all()
        course_orgs = CourseOrg.objects.all()
        return render(request, 'index.html',{
            'all_banners': all_banners,
            'courses': courses,
            'banner_courses': banner_courses,
            'course_orgs': course_orgs,
            'MEDIA_URL':settings.MEDIA_URL
        })